var YAHOO_DATE = 1;
var USER_DATE = 2;
var REAL_TIME_DATE = 3;


//If Firebug is not installed, there will not be js errors :)
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

function getDateAsString(_date)
{
  if(_date == null) return "";
  return _date.getDate()+"/"+(_date.getMonth()+1)+"/"+_date.getFullYear();
}



/**
 * Given a date, this fucntion returns the closer date that allows the
 * retrieval of stock market information
 *
 * @param {Object} _date
 * @param {Object} _days
 */
function getValidDate(_date, _days,_stock)
{
	if(_date == null) return null;

	var date = new Date(_date.getTime());
	if(_days == null) _days = 0;

	date.setDate(date.getDate()- _days);
	date.setHours(0,0,0,0);

	var weekDay = date.getDay();
	if (weekDay==0) date.setDate(date.getDate()-2);
	if (weekDay==6) date.setDate(date.getDate()-1);

	if(isKnownStockClosedDate(_stock,date))
	{
		date = getValidDate(date,1, _stock);
	}

	return date;
}

function isKnownStockClosedDate(_stock,_date)
{
	var stockPos = -1;

	if (_stock==null)
	{
		stockPos = 0;
	}
	else
	{
		for(var j=0;j<STOCK_EXCHANGES.length;j++)
		{
			if(STOCK_EXCHANGES[j]==_stock)
			{
				stockPos = j;
				break
			}
		}
		if(stockPos == -1)  // StockEchange dates not included
			return false;
	}

	for(var i=0;i<STOCK_CLOSED_DATES[stockPos].length;i++)
	{
		if(STOCK_CLOSED_DATES[stockPos][i].getYear()==0)
		{
			if(STOCK_CLOSED_DATES[stockPos][i].getDate()==_date.getDate() && STOCK_CLOSED_DATES[stockPos][i].getMonth()==_date.getMonth())
				return true;
		}
		else if(STOCK_CLOSED_DATES[stockPos][i].getTime() == _date.getTime() )
		 return true;
	}

	return false;
}


function getDate(_strDate, _dateType)
{
	var strDate;
	var resDate ;
	resDate = new Date();

	switch(_dateType)
	{
		case YAHOO_DATE:
						strDate = _strDate.split('-');
						if(strDate.length >= 3)
						{
							if(strDate[0].length==4) //yyyy-mm-dd
								resDate.setFullYear(strDate[0],strDate[1]-1,strDate[2]);
							else					//dd-mmm-yy
								resDate = new Date(strDate[0]+' '+strDate[1]+' 20'+strDate[2]+' ');
						}
						else
							resDate = null;

						break;
		case USER_DATE:
						strDate = _strDate.split('/');
						if(strDate.length >= 3)
						{
							resDate.setFullYear(strDate[2],strDate[1]-1,strDate[0]);
						}
						else
							resDate = null;
						break;
		case REAL_TIME_DATE:
						strDate = _strDate.split('/');
						if(strDate.length >= 3)
						{
							resDate.setFullYear(strDate[2],strDate[0]-1,strDate[1]);
						}
						else
							resDate = null;
						break;
	}
	if(resDate!=null)
		resDate.setHours(0,0,0,0);
	return resDate;

}

function getTableHeadTemplate(_ids,_desc)
{
	var contentData = "";

	contentData += '<tr class="head">';

	for(var i=0;i<_desc.length;i++)
	{
	  if(_ids[i]=="description")
	  {
	  	contentData+=	'<td>'+_desc[i]+'</td>';
	  }
	  else
	  {
	  	contentData+=	'<td align="center">'+_desc[i]+'</td>';
	  }

	}
	contentData += '</tr>';

	return contentData;
}

function getRowsTemplate(_description, _class,_moduleId,_tableFields,_qtdRows)
{
	var i=0;
	var contentData = '';

	contentData += getRowTemplate(_description,_class,_tableFields, _class+i+_moduleId);

	for(i=1;i<_qtdRows;i++)
	{
		contentData += getRowTemplate('',_class,_tableFields, _class+i+_moduleId);
	}

	return contentData;
}

function getRowTemplate(_description,_class,_tableFields, _id)
{
	var contentText= '';
	var i;
	var spanName = _id;

	contentText += '<tr class="'+_class+'" id="'+spanName+'_tr">';

	for(i=0;i<_tableFields.length;i++)
	{
		if(_tableFields[i]=="description")
		{
			contentText += '<td><span id="'+spanName+'_'+_tableFields[i]+'">'+_description+'</span></td>';
		}
		else if(_tableFields[i]=="date")
		{
			contentText += '<td align="center"><span id="'+spanName+'_'+_tableFields[i]+'"><span class="loading">Loading...</span></span></td>';
		}
		else
		{
			contentText += '<td align="center"><span id="'+spanName+'_'+_tableFields[i]+'"></span></td>';
		}

	}

	contentText += '</tr>';


	return contentText;
}



function setRowValue(_conf, _id, _fields, _values)
{
	var contentText = "";
	var color;
	var imgspan = "";
	var spanName;

	var spanId = _id;

	for(var i=0;i<_fields.length;i++)
	{
		spanName = _gel(spanId+'_'+_fields[i]);

		if(_fields[i]=="percent")
		{
			var percent = _values[i];
			imgspan = "";
			spanName.innerHTML ="";
			if(percent!=null)
			{
				if(percent<0)
				{
					spanName.className='percent_down';
					imgspan = '<img src="'+_conf.moduleHostUrl+'resources/img/down_r.gif" alt="Down" border="0" height="14" width="10">';
				}
				else if(percent>0)
		 		{
		 			spanName.className='percent_up';
		 			imgspan = '<img src="'+_conf.moduleHostUrl+'resources/img/up_g.gif" alt="Up" border="0" height="14" width="10">';
		 		}
				else
					spanName.className='percent_still';

				spanName.innerHTML = imgspan;
			}
			else
				percent='-';
			spanName.innerHTML += percent;
		}
		else if(_fields[i]=="date")
		{
			if(_values[i] !=null)
				spanName.innerHTML = getDateAsString(_values[i]);
		}
		else if(_fields[i]=="investmentValue" )
		{
			if(_values[i] !=null && _values[i]!=0)
			{
				spanName.innerHTML = _values[i];
				if(_values[i].constructor == Number)
					spanName.innerHTML = _values[i].toFixed(2);
			}
			else
			{
				spanName.innerHTML ="not available";
			}

		}else if(_fields[i]=="before" || _fields[i]=="after" || _fields[i]=="quoteValue")
		{
			if(_values[i] !=null)
			{
				spanName.innerHTML = _values[i];
				if(_values[i].constructor == Number)
					spanName.innerHTML = _values[i].toFixed(2);
			}
			else
				spanName.innerHTML = '-';

		}
		else if(_fields[i]=="hint")
		{
			var percent = getFieldValue(_fields, _values, "percent");
			var investmentValue = getFieldValue(_fields, _values, "investmentValue");
			if(investmentValue != null && investmentValue ==0)
			{
				percent = null;
			}
			imgspan = "";
			if(percent!=null)
			{
				if(percent >= _conf.thresholdSell  )
				{
					imgspan = '<img src="'+_conf.moduleHostUrl+'resources/img/pinS.gif" alt="Sell" border="0" >';
					spanName.innerHTML =imgspan;
					spanName.title ='Sell it!!!';
				}
				else
				if(percent <= _conf.thresholdBuy)
				{
					imgspan = '<img src="'+_conf.moduleHostUrl+'resources/img/pinB.gif" alt="Buy" border="0" >';
					spanName.innerHTML =imgspan;
					spanName.title ='Buy more!!!';
				}
			}

		}
	}
}




function getFieldValue(_fields, _values, _fieldName)
{
	for(var i=0;i<_fields.length;i++)
	{
		if(_fields[i]==_fieldName)
			return _values[i];
	}

	return null;
}




function updateTableTemplate(_tableId, _qtdRecordsLoaded)
{
	var historyTable = _gel(_tableId);
	var toBeDeleted = historyTable.rows.length - _qtdRecordsLoaded;


	for( var i = 0;i<toBeDeleted;i++)
      {
		historyTable.deleteRow(-1); //deleting last row
      }

}


function getPercentBaseModeString(_conf, _forceDaily)
{
	var calculPercentModeStr = "";

	if(_forceDaily ==null) _forceDaily=false;

	if(_forceDaily || _conf.history_percentBaseMode == "daily")
	{
		calculPercentModeStr = "day before";
	}
	else
	if(_conf.history_percentBaseMode == "last_week")
	{
		calculPercentModeStr = "last week";
	}
	else
	if(_conf.history_percentBaseMode == "last_month")
	{
	    calculPercentModeStr = "last month";
	}
	else
	if(_conf.history_percentBaseMode == "last_6_month")
	{
	   calculPercentModeStr = "last 6 moths";
	}
	else
	if(_conf.history_percentBaseMode == "last_year")
	{
	   calculPercentModeStr = "last year";
	}
	else
	if(_conf.history_percentBaseMode == "last_investment")
	{
	  calculPercentModeStr = "last investement";
	}
	else
	if(_conf.history_percentBaseMode == "first_investment")
	{
	  calculPercentModeStr = "first investment";
	}


	return calculPercentModeStr;
}

function getPercentBaseCotation(_module,_prefs)
{

	var resDate = new Date();
	resDate.setHours(0,0,0,0);
	var cotation = new Cotation();
	var conf = _module.configuration;

	_module.configuration.history_percentBaseMode = _prefs.getString('PERCENT_BASE');
	if(_module.investedValues.length == 0)
	{
	 	conf.history_percentBaseMode = "daily";
	}

  	if(conf.history_percentBaseMode == "last_week")
	{
		resDate.setDate(resDate.getDate()-7);
		if(resDate.getDay()!=1)
		{
			var toMonday = resDate.getDay()-1;
			resDate.setDate(resDate.getDate()-toMonday );
		}
		resDate = getValidDate(resDate,0);
	}
	else
	if(conf.history_percentBaseMode == "last_month")
	{
		resDate.setDate(1);
        resDate.setDate(resDate.getDate()-1);
        resDate = getValidDate(resDate,0);
	}
	else
	if(conf.history_percentBaseMode == "last_6_month")
	{
		resDate.setMonth(resDate.getMonth()-6);
		resDate.setDate(1);
		resDate.setDate(resDate.getDate()-1);
		resDate = getValidDate(resDate,0);
	}
	else
	if(conf.history_percentBaseMode == "last_year")
	{
		resDate.setFullYear(resDate.getFullYear()-1);
		resDate = getValidDate(resDate,0);
	}
	else
	if(conf.history_percentBaseMode == "specific_day")
	{
		var specificDay = _prefs.getString('PERCENT_BASE_SPECIFIC_DAY');
  		if(specificDay == null || specificDay=="")
		{
			_module.messageManager.createDismissibleMessage("The filed \"Specific Date\" must be correctly filled to allow the percentage calcul based on a specific date.");
			conf.history_percentBaseMode == "daily";
		}
		else
		{
			resDate = getDate(_specificDay,USER_DATE);
			resDate = getValidDate(resDate,0);
		}
	}
	else
	if(conf.history_percentBaseMode == "last_investment")
	{
		resDate = _module.getLastInvestment().date;
		resDate = getValidDate(resDate,0);

		if(resDate == null)
		{
			conf.history_percentBaseMode == "daily";
		}
		else
			cotation = 	_module.getLastInvestment().quotesData[0].cotation;

	}
	else
	if(conf.history_percentBaseMode == "first_investment")
	{
		resDate = _module.getFirstInvestment().date;
		resDate = getValidDate(resDate,0);

		if(resDate == null)
		{
			conf.history_percentBaseMode == "daily";
		}
		else
			cotation = 	_module.getFirstInvestment().quotesData[0].cotation;

	}
	else
	if(conf.history_percentBaseMode == "daily")
	{
		cotation = null;
	}

	if(cotation!=null)
		cotation.date = resDate;

	return cotation;
}

function  orderDescByDate(e1, e2)
{
	if  (e1.date.getTime() < e2.date.getTime())
		return 1;
	else if (e1.date.getTime()> e2.date.getTime())
		return -1;
    else
		return 0;

}

function getPercentValue(_currentValue, _baseValue)
{
	var res = _currentValue /_baseValue;
	res = (res * 100) - 100;
	var percent = res.toFixed(2);
	return percent;
}

function getPercent(_quotes, _date, _baseCotation)
{
	var j;
	var currentValue =0;
	var baseValue =100; //could be any value
	var percent;
	var res;

	if(_quotes.constructor==Quote)
	{
		var quote = _quotes;
		_quotes = new Array();
		_quotes.push(quote);
	}

	for(j=0;j<_quotes.length;j++)
	{
		res = getHipotheticalValue(_quotes[j],_date, _baseCotation, baseValue);
		if(res ==null)
		{
			return null;
		}
		else
		 currentValue += res;
	}

	return getPercentValue(currentValue, baseValue);

}


//Given a _investedDate an an _investedValue it returns the invested value for the _date
function getHipotheticalValue(_quote,_date, _investedCotation, _investedValue)
{
	var purchasedQuantity;
	var res;
	var cotation;

	if(_investedCotation!=null && _investedCotation.value == null)
	{
		_investedCotation = _quote.getCotation(_investedCotation.date);
	}

	var today = new Date();
	today.setHours(0,0,0,0);

	if(today.getTime() == _date.getTime())
	{
		cotation = _quote.currentCotation;
	}
	else
	{
		var cotation = _quote.getCotation(_date);
	}


	if(cotation !=null && _investedCotation!=null)
	{
		_investedValue = _quote.compositionPercent * _investedValue / 100;
		purchasedQuantity = _investedValue / _investedCotation.value;
		res = purchasedQuantity * cotation.value;
	}
	else
	{
		res = null;
	}


	return res;


}

function getToogleArrow(_conf, _tableId)
{
	var content ='';
	var imgId = _tableId+'_imageToggle';
	var funcCall = "onclick='toggleTable(\""+_tableId+"\",\""+imgId+"\",\""+_conf.moduleHostUrl+"\")'";

	content += "<img id='"+imgId+"' src='"+_conf.moduleHostUrl+"resources/img/arrow_show.gif' alt='Show'  border='0' "+funcCall+" />";

	return content;
}

function toggleTable(_tableId, _imageId, _hostPath)
{
	var tableStyle = _gel(_tableId).style;

	toggleLayer(_tableId);

	var imageSection = _gel(_imageId);

	if(tableStyle.display=="block")
	{
		imageSection.src=_hostPath+"resources/img/arrow_hide.gif";
	}
	else
	{
		imageSection.src=_hostPath+"resources/img/arrow_show.gif";
	}



}

 function toggleLayer(whichLayer)
{
	if (document.getElementById)
	{
		// this is the way the standards work
		var style2 = document.getElementById(whichLayer).style;

		if (style2.display=="block" || style2.display=="")
			style2.display = "none";
		else
			style2.display = "block";

	}
	else if (document.all)
	{
		// this is the way old msie versions work
		var style2 = document.all[whichLayer].style;
		style2.display = "block";
		if (style2.display=="block" || style2.display=="")
			style2.display = "none";
		else
			style2.display = "block";
	}
	else if (document.layers)
	{
		// this is the way nn4 works
		var style2 = document.layers[whichLayer].style;
		style2.display = "block";
		if (style2.display=="block" || style2.display=="")
			style2.display = "none";
		else
			style2.display = "block";
	}

	_IG_AdjustIFrameHeight();
 }

function toggleElements(arrayElements)
{

	for (i=0;i<arrayElements.length;i++)
	{
		toggleLayer(arrayElements[i]);
	}

}
